package leeon.mobile.BBSBrowser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import leeon.kaixin.wap.action.LoginAction;
import leeon.kaixin.wap.action.PictureAction;
import leeon.kaixin.wap.action.StatusAction;
import leeon.kaixin.wap.models.Repaste;
import leeon.kaixin.wap.models.Status;
import leeon.kaixin.wap.models.StatusPic;
import leeon.kaixin.wap.models.StatusRepaste;
import leeon.kaixin.wap.models.StatusType;
import leeon.kaixin.wap.util.HttpUtil;
import leeon.mobile.BBSBrowser.UIUtil.ImageLoadedCacheFileHandle;
import leeon.mobile.BBSBrowser.models.BoardObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class KaixinMainActivity extends ListActivity {
	
	
	static BoardObject board;
	static List<BoardObject> boardlist;
	
	private List<Status> list;
	private boolean onlyLogin = false;
	
	private TextView title;	
	private Handler handler = new Handler();
	
	static String verify = null;
	static String email = null;
	
	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		super.onCreate(savedInstanceState);
		
		board = (BoardObject)this.getIntent().getSerializableExtra("board");
		boardlist = (List<BoardObject>)(this.getIntent().getSerializableExtra("boardlist"));
		onlyLogin = this.getIntent().getBooleanExtra("onlyLogin", false);
		
		list = new ArrayList<Status>();
		getListView().setBackgroundColor(Color.WHITE);
		getListView().setDivider(getResources().getDrawable(R.drawable.kaixin_divider));
		setListAdapter(new StatusListAdapter(list));
		scrollAction.addActionWhenScroll(getListView());
		
		if (customTitleSupported) {
			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.kaixin_titlebar);
			title = (TextView)findViewById(R.id.kaixinTitle);
		}
		
		if (verify == null) {
			loginKaixin(true);
		} else {
			scrollAction.refresh();
			title.setText(email);
		}
	}
	
	@Override 
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
		}
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, final int position, long id) {
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, 1, 1, "切换账号").setIcon(android.R.drawable.ic_menu_myplaces);
		menu.add(0, 2, 2, "刷新动态").setIcon(android.R.drawable.ic_menu_rotate);
        return result;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			loginKaixin(false);
			break;
		case 2:
			scrollAction.refresh();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void listKaixin(final int totalItemCount) {
		UIUtil.runActionInThread(this, new UIUtil.ActionInThread<Status>() {
			@Override
			public void action() throws NetworkException, ContentException {
				if (verify != null) {
					if (list.size() == 0)
						bglist = StatusAction.listStatus(verify);
					else
						bglist = StatusAction.listStatus(verify, totalItemCount);
				}
			}
			@Override
			public void actionFinish() {
				if (bglist != null) {
					list.addAll(bglist);
					((BaseAdapter)KaixinMainActivity.this.getListView().getAdapter()).notifyDataSetChanged();
				}
			}
			
			@Override
			public void actionError() {
				scrollAction.rollback();
			}
		});
	}
	
	private void loginKaixin(final boolean autoLogin) {
		View view = LayoutInflater.from(this).inflate(R.layout.weibo_login_dialog, null);
		final EditText et1 = (EditText)view.findViewById(R.id.wbUser);
		final EditText et3 = (EditText)view.findViewById(R.id.wbPassword);
		final CheckBox cm = (CheckBox)view.findViewById(R.id.wbRecordPassword);
		
		String p = UserUtil.getKaixinPassword(this);
		et1.setText(UserUtil.getKaixinUser(this));
		et3.setText(p);
		
		if (autoLogin && SettingActivity.autoLoginKaixin(this)) {
			if (p != null && p.length() != 0) {
				login(et1.getText().toString(), et3.getText().toString(), cm.isChecked());
				return;
			}
		}

		new AlertDialog.Builder(this)
			.setTitle("登录开心网")
			.setView(view)
			.setCancelable(false)
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {					
				public void onClick(DialogInterface dialog, int which) {
					login(et1.getText().toString(), et3.getText().toString(), cm.isChecked());
				}
			})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					if (autoLogin) KaixinMainActivity.this.finish();
				}
		}).create().show();
	}
	
	
	private void login(final String userId, final String passWord, final boolean saveIt) {
		UIUtil.runActionInThread(this, new UIUtil.ActionInThread<Status>() {
			@Override
			public void action() throws NetworkException, ContentException {
				if (verify != null) LoginAction.logout(verify);
				verify = LoginAction.login(userId, passWord, LoginAction.home());
				email = userId;
			}
			@Override
			public void actionFinish() {
				if (saveIt) UserUtil.saveKaixinUserInfo(KaixinMainActivity.this, userId, passWord);
				if (onlyLogin) 
					KaixinMainActivity.this.finish();
				else
					scrollAction.refresh();
				title.setText(email);
			}
			@Override
			public void actionError() {
				verify = null;
				email = null;
				if (onlyLogin) 
					KaixinMainActivity.this.finish();
				else {
					scrollAction.actionClear();
					((BaseAdapter)KaixinMainActivity.this.getListView().getAdapter()).notifyDataSetChanged();
				}
				title.setText("没有登录");
			}
		});
	}
	
	public static String getKaixinVerify(Context context) {
		if (verify == null) {
			context.startActivity(new Intent(context, KaixinMainActivity.class).putExtra("onlyLogin", true));
		}
		return verify;
	}
	
	private KaixinListScrollAction scrollAction = new KaixinListScrollAction();
	private class KaixinListScrollAction extends UIUtil.ActionInScroll {
		
		public KaixinListScrollAction() {
			new UIUtil().super();
		}
		
		@Override
		protected void actionClear() {
			list.clear();
		}

		@Override
		protected void actionScroll(int totalItemCount) {
			listKaixin(totalItemCount);
		}

		@Override
		protected void actionRemove(Object o) {
			list.remove(o);
		}
		
		@Override
		protected int pageSize() {
			return 10;
		}
		
	}
	
	private class StatusListAdapter extends BaseAdapter {

		private List<Status> list;

		public StatusListAdapter(List<Status> list) {
			this.list = list;
		}

		public int getCount() {
			return list.size();
		}

		public Object getItem(int position) {
			return list.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View tv;
			if (convertView == null) {
				tv = LayoutInflater.from(KaixinMainActivity.this).inflate(R.layout.kaixin_status_item, parent, false);
			} else {
				tv = convertView;
			}
			
			TextView text1 = (TextView)tv.findViewById(R.id.statusUserName);
			TextView text2 = (TextView)tv.findViewById(R.id.statusContent);
			TextView text3 = (TextView)tv.findViewById(R.id.statusTime);
			TextView text4 = (TextView)tv.findViewById(R.id.statusInfo);
			
			ImageView icon = (ImageView)tv.findViewById(R.id.statusUserIcon);
			ImageView img = (ImageView)tv.findViewById(R.id.statusImage);
			Status s = list.get(position);
			
			text4.setVisibility(View.INVISIBLE);
			img.setVisibility(View.GONE);
			text1.setText(s.getUname());
			text3.setText(s.getDate());
			loadIcon(LoginAction.uicon(s.getUid()), icon);
			if (StatusType.转帖.equals(s.getType())) {
				StatusRepaste r = (StatusRepaste)s;
				text2.setText(renderRepaste(r));
				
				text4.setVisibility(View.VISIBLE);
				text4.setText(renderIntentLink(r.getNewRepasteCount() + "条新转帖>>", 
					new Intent(KaixinMainActivity.this, KaixinRepasteActivity.class)
					.putExtra("uid", r.getUid())
					.putExtra("uname", r.getUname())));
			} else if (StatusType.照片.equals(s.getType())) {
				StatusPic p = (StatusPic)s;
				text2.setText(p.getContent());
				loadImage(p, img);
				
				text4.setVisibility(View.VISIBLE);
				text4.setText(renderIntentLink("查看相片>>", 
					new Intent(KaixinMainActivity.this, KaixinPictureActivity.class).putExtra("status", p)));
			} else {
				if (s.getContent() != null)
					text2.setText(renderURL((Spannable)Html.fromHtml(s.getContent()), handler, text2));
			}
			
			text2.setMovementMethod(LinkMovementMethod.getInstance());
			text4.setMovementMethod(LinkMovementMethod.getInstance());
			
			if (position%2 == 1) {
				tv.setBackgroundResource(R.drawable.kaixin_selector1);
				text1.setBackgroundDrawable(getResources().getDrawable(R.drawable.kaixin_bg1));
			} else {
				tv.setBackgroundResource(R.drawable.kaixin_selector2);
				text1.setBackgroundDrawable(getResources().getDrawable(R.drawable.kaixin_bg2));
			}
			return tv;
		}		
	}
	
	
	private void loadIcon(final String src, final ImageView i) {
		if (src != null && src.length() != 0) {
			i.setVisibility(View.VISIBLE);
			i.setImageDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
			UIUtil.loadImageInThread(src, this, 
				new ImageLoadedCacheFileHandle() {
				public void imageFileLoadedCallback(final File file, String type) {
					handler.post(new Runnable() {
						public void run() {
							i.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
						}
					});
				}
			});
		} else {
			i.setVisibility(View.GONE);
		}
	}
	
	private void loadImage(final StatusPic s, final ImageView i) {
		i.setVisibility(View.VISIBLE);
		i.setImageDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
		new Thread() {
			public void run() {
				try {
					if (s.getUrl() == null) PictureAction.detailPicture(verify, s, "0");
				} catch (NetworkException e) {
					Log.i("kaixin", "load main image error", e);
				}
				if (s.getUrl() == null) return;
				UIUtil.loadImageInThread(s.getUrl(), KaixinMainActivity.this, handler, i, HttpUtil.newInstance());
			}
		}.start();
	}
	
	private Spannable renderIntentLink(String text, final Intent i) {
		SpannableStringBuilder ssb = new SpannableStringBuilder();
		ssb.append(text);
		ssb.setSpan(new ClickableSpan() {
			@Override
			public void onClick(View widget) {
				if (i != null)
					KaixinMainActivity.this.startActivity(i);
			}
			@Override
		    public void updateDrawState(TextPaint ds) {
		        super.updateDrawState(ds);
		        ds.setUnderlineText(false);
		        ds.setColor(getResources().getColor(R.color.kaixin_tag1));
		    }

		}, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		return ssb;
	}
	
	private Spannable renderRepaste(final StatusRepaste sr) {
		SpannableStringBuilder ssb = new SpannableStringBuilder("转帖给大家：\n");
		for (final Repaste r : sr.getNewRepasteList()) {
			int s = ssb.length();
			ssb.append(r.getTitle());
			ssb.setSpan(new ClickableSpan() {
				@Override
				public void onClick(View widget) {
					KaixinMainActivity.this.startActivity(
						new Intent(KaixinMainActivity.this, KaixinRepasteDetailActivity.class)
							.putExtra("repaste", r)
							.putExtra("uname", sr.getUname()));
				}
				@Override
			    public void updateDrawState(TextPaint ds) {
			        super.updateDrawState(ds);
			        ds.setUnderlineText(false);
			        ds.setColor(getResources().getColor(R.color.kaixin_tag1));
			    }

			}, s, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			ssb.append("\n");
		}
		return ssb;
	}

	
	private Spannable renderURL(Spannable content, Handler handler, TextView t) {
		UIUtil.renderBaseURL(content, HttpUtil.KAIXIN_URL, false, this.getResources().getColor(R.color.kaixin_tag1));
		UIUtil.renderImage(content, HttpUtil.KAIXIN_URL, handler, t);
		return content;
	}
}
